package com.rc.saas.tenant.service.enterprise;

import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberShareMapper;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmemberShare;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmemberShareExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date 2021/3/12
 */
@Service
public class EnterpriseSubmemberShareServiceImpl implements EnterpriseSubmemberShareService {

    @Autowired
    private EnterpriseSubmemberShareMapper enterpriseSubmemberShareMapper;


    @Override
    public EnterpriseSubmemberShareMapper getMapper() {
        return enterpriseSubmemberShareMapper;
    }

    @Override
    public EnterpriseSubmemberShare selectByMemberId(Long memberId) {
        EnterpriseSubmemberShareExample example = new EnterpriseSubmemberShareExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        List<EnterpriseSubmemberShare> enterpriseSubmemberShares = enterpriseSubmemberShareMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(enterpriseSubmemberShares)) {
            return enterpriseSubmemberShares.get(0);
        }
        return null;
    }

    @Override
    public void submemberShareTask() {
        Date now = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        //判断今天是周几
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        List<EnterpriseSubmemberShare> weekList = enterpriseSubmemberShareMapper.listByShareType("1");

        List<EnterpriseSubmemberShare> monthList = enterpriseSubmemberShareMapper.listByShareType("2");

        ArrayList<Long> needUpdateData = new ArrayList<>();

        if (!CollectionUtils.isEmpty(weekList)) {
            for (EnterpriseSubmemberShare submemberShare : weekList) {
                calendar.setTime(submemberShare.getBeginTime());
                int setDate = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                if (setDate == week) {
                    needUpdateData.add(submemberShare.getSubmemberShareId());
                }
            }
        }

        if (!CollectionUtils.isEmpty(monthList)) {
            for (EnterpriseSubmemberShare submemberShare : monthList) {
                long l = (System.currentTimeMillis() - submemberShare.getBeginTime().getTime()) / (1000 * 60 * 60 * 24);
                if (l % 30 == 0) {
                    needUpdateData.add(submemberShare.getSubmemberShareId());
                }
            }
        }

        //更新每天每日限制数据
        enterpriseSubmemberShareMapper.updateClearBalance();
        //更新月和周
        if (!CollectionUtils.isEmpty(needUpdateData)) {
            enterpriseSubmemberShareMapper.updateBatchClear(needUpdateData);
        }

    }
}
